module cl {
	export class System {

		//背景音乐

		private static musicHistory : number[] = [-1];

		private static musics : string[] = ["Armored Cars_mp3", "CALL OF DUTY_mp3", "Electric Romeo_mp3", "Main Theme_mp3", "圣魔浩荡_mp3"];

		public static musicChannel : egret.SoundChannel;

		public static musicEnable : boolean = true;

		public static playBgm() : void {
			if (! System.musicEnable){
				return;
			}
			let musicid = Math.floor(Math.random() * System.musics.length);
			while (musicid == System.musicHistory[System.musicHistory.length - 1] || musicid == System.musicHistory[System.musicHistory.length - 2]) {
				musicid = Math.floor(Math.random() * System.musics.length);
			}
			System.musicHistory.push(musicid);
			System.musicChannel = (RES.getRes(System.musics[musicid]) as egret.Sound).play(0, 1);

			System.musicChannel.addEventListener(egret.Event.SOUND_COMPLETE, System.playBgm, null);
		}

		public static stopCurrentBgm() : void {
			if (System.musicChannel != null) {
				System.musicChannel.stop();
			}
		}

		public static enableBgm(enable : boolean) : void {
			System.musicEnable = enable;
			if (enable) {
				System.playBgm();
			} else {
				System.stopCurrentBgm();
			}
		}

		// 按钮音效等

		public static soundChannel : egret.SoundChannel;

		public static soundEnable : boolean = true;

		/**
         * 遍历所有成员，如果有 Button 类型，则为其 touchBegin 事件添加 click 声音
         */
        public static clickSoundToAllButton(container) : void {
            for (let member in container) {
                if (container[member] instanceof eui.Button) {
                    (<eui.Button>container[member]).addEventListener("touchBegin", ()=>{
						if (System.soundEnable) {
							System.soundChannel = (RES.getRes("click_mp3") as egret.Sound).play(0, 1);
						}
                    }, null);
                }
            }
        }

		public static stopCurrentSound() : void {
			if (System.soundChannel != null) {
				System.soundChannel.stop();
			}
		}

		public static enableSound(enable : boolean) : void {
			System.soundEnable = enable;
			if (! enable) {
				System.stopCurrentSound();
			}
		}
	}
}